package com.anzia.storeback.service.impl;

import com.anzia.storeback.dao.ResourceDao;
import com.anzia.storeback.entity.Carousel;
import com.anzia.storeback.service.ResourceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 *@ClassName ResourceServiceImpl
 *@Description
 *@Author Anzia.
 *@Date 2021/5/31 22:47
 *@Version 1.0
 **/
@Service("resourceService")
public class ResourceServiceImpl implements ResourceService {

    @Autowired
    private ResourceDao resourceDao;

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public List<Carousel> getCarousel() {

        // 从数据库中获取该key的键值对
        Map<Object, Object> carousel = redisTemplate.opsForHash().entries("carousel");
        // 如果redis中没有该数据，则从数据库中获取
        if (carousel.isEmpty()) {
            List<Carousel> carouselList = resourceDao.getCarousel();
            carousel.put("carousel", carouselList);
            // 获取完后再在数据库中存一份
            redisTemplate.opsForHash().putAll("carousel", carousel);
        }

        return (List<Carousel>) carousel.get("carousel");
    }
}
